import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

@Injectable()
export class AuthoritiesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    //从控制器注解中得到权限列表
    const authorities = this.reflector.get<string[]>('authorities', context.getHandler());
    if (!authorities) return true;

    const request = context.switchToHttp().getRequest();
    const user = request.user;

    const hasAuthority = () => user.guardList.some(authority => authorities.includes(authority));
    return user && user.guardList && hasAuthority();
  }
}
